let currentPage = 1;  // 当前页
const pageSize = 10;   // 每页显示的点名记录数
const apiUrl = "http://localhost:8083/api"; // 后端 API 基础地址

// 获取点名记录
function loadAttendanceData(courseFilter = "", statusFilter = "") {
  const attendanceList = document.querySelector("#attendance-table tbody");
  attendanceList.innerHTML = "";  // 清空现有的点名记录

  // 构造请求 URL 和参数
  const url = `${apiUrl}/student/learning/course/${courseFilter}/roll-calls?pageNum=${currentPage}&pageSize=${pageSize}`;

  // 请求后端接口获取点名记录
  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      // 需要传递认证 token 或其他身份信息
      'Authorization': `Bearer ${localStorage.getItem("token")}`  // 假设 token 存储在 localStorage 中
    }
  })
  .then(response => response.json())
  .then(data => {
    if (data.code === 200 && data.data) {
      const rollCallData = data.data.records;  // 获取点名记录
      renderAttendanceData(rollCallData);  // 渲染点名记录
      updatePaginationButtons(data.data.total);  // 更新分页按钮
    } else {
      alert("加载点名数据失败");
    }
  })
  .catch(error => {
    console.error('Error fetching attendance data:', error);
    alert("加载点名数据失败");
  });
}

// 渲染点名记录到表格
function renderAttendanceData(rollCallData) {
  const attendanceList = document.querySelector("#attendance-table tbody");

  rollCallData.forEach(record => {
    const row = document.createElement("tr");

    row.innerHTML = `
      <td>${record.course}</td>
      <td>${record.date}</td>
      <td>${record.status}</td>
      <td>
        ${record.status === "缺席" ? `<button onclick="viewAbsenceReason('${record.rollCallId}')">查看缺席原因</button>` : ''}
      </td>
    `;
    attendanceList.appendChild(row);
  });
}

// 查看缺席原因
function viewAbsenceReason(rollCallId) {
  alert("查看缺席原因: 记录 ID " + rollCallId);
}

// 筛选点名记录 - 按课程
function filterAttendanceByCourse() {
  const selectedCourse = document.getElementById("attendance-course").value;
  loadAttendanceData(selectedCourse);
}

// 筛选点名记录 - 按状态
function filterAttendanceByStatus() {
  const selectedStatus = document.getElementById("attendance-status").value;
  loadAttendanceData("", selectedStatus);
}

// 分页 - 下一页
function nextPage() {
  currentPage++;
  loadAttendanceData();
}

// 分页 - 上一页
function previousPage() {
  if (currentPage > 1) {
    currentPage--;
    loadAttendanceData();
  }
}

// 更新分页按钮的状态
function updatePaginationButtons(totalRecords) {
  const prevButton = document.querySelector(".pagination button:first-child");
  const nextButton = document.querySelector(".pagination button:last-child");

  const totalPages = Math.ceil(totalRecords / pageSize);

  if (currentPage <= 1) {
    prevButton.disabled = true;
  } else {
    prevButton.disabled = false;
  }

  if (currentPage >= totalPages) {
    nextButton.disabled = true;
  } else {
    nextButton.disabled = false;
  }
}

// 页面加载时调用
document.addEventListener("DOMContentLoaded", function() {
  loadAttendanceData();  // 加载点名数据
});

// 退出按钮点击事件
const logoutBtn = document.getElementById('logout-btn');
logoutBtn.addEventListener('click', () => {
  localStorage.removeItem('token'); // 清除 token
  window.location.href = '../login.html'; // 跳转到登录页面
});
